<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../store/user'
import { showToast } from 'vant'

const router = useRouter()
const userStore = useUserStore()

// 表单数据
const formData = reactive({
  username: '',
  password: ''
})

// 表单校验规则
const rules = {
  username: [{ required: true, message: '请输入用户名' }],
  password: [{ required: true, message: '请输入密码' }]
}

// 登录loading
const loading = ref(false)

// 登录方法
const onSubmit = async () => {
  try {
    loading.value = true
    const res = await userStore.loginAction(formData.username, formData.password)
    // 登录后获取用户信息
    if (res.data && res.data.access_token) {
      await userStore.getUserInfoAction()
      showToast('登录成功')
      router.push('/home')
    } else {
      showToast('登录失败')
    }
  } catch (error: any) {
    console.log(error)
    // showToast(error.message || '登录失败')
  } finally {
    loading.value = false
  }
}

// 去注册页面
const goToRegister = () => {
  router.push('/register')
}
</script>

<template>
  <div class="login-container">
    <div class="login-form">
      <h2 class="login-title">游客登录</h2>
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="formData.username"
            name="username"
            label="用户名"
            placeholder="请输入用户名"
            :rules="rules.username"
          />
          <van-field
            v-model="formData.password"
            type="password"
            name="password"
            label="密码"
            placeholder="请输入密码"
            :rules="rules.password"
          />
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit" :loading="loading">
            登录
          </van-button>
          <div class="register-link" @click="goToRegister">
            没有账号？去注册
          </div>
        </div>
      </van-form>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f7f8fa;
}

.login-form {
  width: 90%;
  max-width: 600px;
  padding: 20px;
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #323233;
}

.register-link {
  text-align: center;
  margin-top: 16px;
  color: #1989fa;
  font-size: 14px;
}
</style> 